package com.lsa.southwind.controller;


import com.lsa.southwind.entity.Student;
import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.form.StudentForm;
import com.lsa.southwind.service.StudentService;
import com.lsa.southwind.util.ResultVoUtil;
import com.lsa.southwind.vo.PageVo;
import com.lsa.southwind.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @PostMapping("/save")
    public ResultVo saveStudent(@RequestBody Student student) {
        Boolean saveStudent = this.studentService.saveStudent(student);
        if (!saveStudent) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }

    @GetMapping("/list/{page}/{size}")
    public ResultVo listStudent(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageVo studentlist = this.studentService.list(page, size);
        return ResultVoUtil.success(studentlist);
    }

    @GetMapping("/search")
    public ResultVo searchStudent(SearchForm searchForm) {
        PageVo search = this.studentService.search(searchForm);
        System.out.println("查询出的数据:" + ResultVoUtil.success(search));
        return ResultVoUtil.success(search);
    }

    /*学生修改功能*/
    @GetMapping("/findById/{id}")
    public ResultVo findByIdStudent(@PathVariable("id") Integer id) {
        /*通过id查询出学生全部信息*/
        Student studentById = this.studentService.getById(id);
        StudentForm studentForm = new StudentForm();
        /*把查询出来的所有学生信息全部复制给studentForm*/
        BeanUtils.copyProperties(studentById, studentForm);
        studentForm.setOldDormitoryId(studentById.getDormitoryId());
        return ResultVoUtil.success(studentForm);
    }

    @PutMapping("/update")
    public ResultVo updateStudent(@RequestBody StudentForm studentForm) {
        Boolean update = this.studentService.update(studentForm);
        if (!update) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }

    }

    /*学生删除功能*/
    @DeleteMapping("/deleteById/{id}")
    public ResultVo deleteByIdStudent(@PathVariable("id") Integer id) {
        Boolean deleteById = this.studentService.deleteById(id);
        if (!deleteById) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }

    }

}

